package controller;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import org.activiti.engine.task.Task;

import wfm.activiti.ActivitiManager;
import wfm.entities.Ticket;
import wfm.entities.User;
import wfm.entities.WFInfo;
import wfm.query.QueryDao;

import com.web.util.WebUtils;

@ManagedBean(name = "prepareProtocolController")
@SessionScoped
public class PrepareProtocolController {
	@ManagedProperty(value = "#{hoursNeeded}")
	private Double hoursNeededForRepair;

	@ManagedProperty(value = "#{ticket}")
	private Ticket ticket;

	@ManagedProperty(value = "#{wfInfo}")
	private WFInfo wfInfo;

	@ManagedProperty(value = "#{user}")
	private User user;

	public PrepareProtocolController() {

	}

	@PostConstruct
	public void init() {
		ticket=(Ticket)QueryDao.getVariableToProcessById(wfInfo.getInstanceId(), "ticket");
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public WFInfo getWfInfo() {
		return wfInfo;
	}

	public void setWfInfo(WFInfo wfInfo) {
		this.wfInfo = wfInfo;
	}

	public Double getHoursNeededForRepair() {
		return hoursNeededForRepair;
	}

	public void setHoursNeededForRepair(Double hoursNeededForRepair) {
		this.hoursNeededForRepair = hoursNeededForRepair;
	}

	public Ticket getTicket() {
		return ticket;
	}

	public void setTicket(Ticket ticket) {
		this.ticket = ticket;
	}

	public String finish() {
		String nextPage = "myTasks";
		ticket.setEstimatedRepairDuration(this.ticket.getEstimatedRepairDuration());
		QueryDao.saveVariableToProcessById(wfInfo.getInstanceId(), "ticket",
				ticket);

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(wfInfo.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = wfInfo.getInstanceId();

		Task task = QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);

		if (task != null) {
			wfInfo.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(wfInfo.getTaskId());
		}

		return WebUtils.redirect(nextPage);

	}
	
	public String convertFault(){
		return (ticket.getFault()==0) ? "thid party negligence" : "personal negligence";
	}

}
